package jaux.tank.dao;

import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

import javax.persistence.EntityManager;
import javax.persistence.metamodel.EntityType;
import javax.transaction.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.support.SimpleJpaRepository;
import org.springframework.stereotype.Component;

import jaux.tank.bean.vo.EntityQueryCondition;
import jaux.tank.dao.utils.JpaUtils;

@Component
public class GeneralRepository {

	@Autowired
	private EntityManager em;
	
	private Map<EntityType,SimpleJpaRepository> repoMap = new HashMap<>();

	public Page<Object> findAll(EntityType<?> entityType, Pageable convertPageToPageable) {
		return getEntityRepository(entityType).findAll(convertPageToPageable);
	}
	public Page<Object> findAll(EntityType<?> entityType, List<EntityQueryCondition> queryConditionLst,
			Pageable pageable) {
		return getEntityRepository(entityType).findAll(JpaUtils.genPredicateByConditions(queryConditionLst, entityType.getJavaType()), pageable);
	}
	
	public Optional<Object> findById(EntityType<?> entityType, Object realEntityid) {
		return getEntityRepository(entityType).findById(realEntityid);
	}

	@Transactional
	@Modifying
	public Object save(EntityType<?> entityType, Object readValue) {
		return getEntityRepository(entityType).save(readValue);
	}
	@Transactional
	@Modifying
	public Collection<Object> saveAll(EntityType<?> entityType, Collection<?> readValue) {
		return getEntityRepository(entityType).saveAll(readValue);
	}

	@Transactional
	@Modifying
	public void deleteById(EntityType<?> entityType, Object realEntityid) {
		   getEntityRepository(entityType).deleteById(realEntityid);
	}
	private SimpleJpaRepository getEntityRepository(EntityType<?> entityType) {
		if(repoMap.get(entityType)==null) {
			repoMap.put(entityType, new SimpleJpaRepository(entityType.getJavaType(), em));
		}
		return repoMap.get(entityType);
	}

}
